package com.djsearch.ui;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.json.JSONException;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.djsearch.R;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.data.ImageManager;
import com.djsearch.util.AsyncImageLoader;
import com.djsearch.util.AsyncImageLoader.ImageCallback;
import com.djsearch.widget.HandImgDialog;
import com.djsearch.widget.HandImgDialog.HandImgListener;;
/**
 * 编辑个人信息页面
 * @author chenyang2
 * @param <FileStream>
 *
 */
public class EditMyInfoActivity<FileStream> extends BaseActivity{
	
	private Context mContext;
	private ImageView myPhotoImg;
	private Uri mImgUri;
	private TextView saveText,handHeadImg;
	private AsyncImageLoader asyncImageLoader;
	private Button btnBack;
	private Bitmap asSaveBitmap, bitmap;
	private View view;
	private HandImgDialog handImgDialog;
	private TextView carmeraImg,fileImg;
	private DisplayMetrics displayMetrics ;
	private int width;
	private int height;
	private EditText newNameEdit,newPassWordEidt;
	private byte[] imgByte;
	private String bitmapAsStr;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mContext = this;
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		setContentView(R.layout.edit_myinfo_layout);
		asyncImageLoader = new AsyncImageLoader("");
		initView();
		initOnClick();
	}
	
	
	

	/**
	 * 提交数据
	 * 
	 * "userId":"8765","newUserId":"","newPassword":""
	 * 
	 */
	private void requestHandInfo() {
		IRequest request = new JSONReq("edit_info");
		request.putParam("userId", preferences.getString("userId", ""));
		request.putParam("newUserId",newNameEdit.getText().toString() );
		request.putParam("newPassword", newPassWordEidt.getText().toString());
//		request.putParam("headImg", imgByte);
		request.putParam("headImg", bitmapAsStr);
//		String headImgStr = getStringFromByte(imgByte);
//		String s = imgByte.toString();
//		byte[] bs=System.Text.Encoding.GetEncoding("GB2312").GetBytes(s);
//		String encoding="UTF-8";
//		try {
//			byte[] bytes_=s.getBytes(encoding);
//		} catch (UnsupportedEncodingException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}  

		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
				showDialog("正在提交...");
			}
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
				    try {
						Toast.makeText(mContext, response.getString("message"), 5000).show();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					getDataToResolve(response);
				} else if (IResponse.Fail==result) {
					try {
						Toast.makeText(mContext, response.getString("message"), 5000).show();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
					missDialog();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
				missDialog();
			}
			
		});
	
		
	}
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		//从本地选择
		if (resultCode == RESULT_OK && requestCode == 1 ) {
			mImgUri = data.getData();
			ContentResolver cr = this.getContentResolver();
			try {
				bitmap = BitmapFactory.decodeStream(cr.openInputStream(mImgUri));
				asSaveBitmap = bitmap;
				if(bitmap == null){
					return;
				} else {
					Bitmap toSetPhotoImg = ImageManager.resizeImage(bitmap, 150.0f);
					myPhotoImg.setImageBitmap(toSetPhotoImg);
					bitmapAsStr = bitmaptoString(toSetPhotoImg);
					imgByte = getBitmapAsByte(toSetPhotoImg);
//					Bitmap bit = getByteAsBimap(imgByte);
//					Bitmap bitMap = stringtoBitmap(bitmapStr);
//					myPhotoImg.setImageBitmap(bitMap);
//					if (bitmap != null && !bitmap.isRecycled()) {
//						bitmap.recycle();
//					}
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		//照相机
		if (resultCode == RESULT_OK && requestCode == 0 ) {
			Bitmap bitmap = BitmapFactory.decodeFile(ImageManager.PHOTO_PATH + "headImage.jpg");
			if (bitmap != null) {
				Bitmap toSetPhotoImg = ImageManager.resizeImage(bitmap, 150.0f);
				myPhotoImg.setImageBitmap(toSetPhotoImg);
			}
//			if (bitmap != null && !bitmap.isRecycled()) {
//				bitmap.recycle();
//			}
		}	
	}
	
	
	public void getDisPlayMetrics(){
		displayMetrics = new DisplayMetrics();
	    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
	    width =  displayMetrics.widthPixels;
	}
	
	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			EditMyInfoActivity.this.finish();
			overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
		}
		return false;
	}
	
	class ImgAlterDialogClickListener  implements DialogInterface.OnClickListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch(which) {
			    //相机
		    	case 0:
		    	{  
		    		File tempfile = new File(ImageManager.PHOTO_PATH + "HeadImg/" + "headImage.jpg");
		    		try {
						tempfile.createNewFile();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		    		Intent localIntent = new Intent("android.media.action.IMAGE_CAPTURE");
		    	    Uri localUri = Uri.fromFile(tempfile);
		    	    localIntent.putExtra("output", localUri);
		    	    startActivityForResult(localIntent, 0);
		    		break;
			    }
		    	//本地图片
		    	case 1:
		    	{
		    		Intent intent = new Intent();
		    		intent.setType("image/*");
		    		intent.setAction(Intent.ACTION_GET_CONTENT);
		    		intent.addCategory(Intent.CATEGORY_OPENABLE);   
		    		startActivityForResult(intent,1);
		    		break;
			    }			
			}
			dialog.dismiss();
		}	
		
	}

	@Override
	void initHandler() {
		// TODO Auto-generated method stub
		
	}



	@Override
	void initView() {
		btnBack = (Button)findViewById(R.id.btnBack);
		myPhotoImg = (ImageView)findViewById(R.id.myPhotoImg);
		saveText = (TextView)findViewById(R.id.saveText);
		handHeadImg = (TextView)findViewById(R.id.handHeadImg);
		newNameEdit = (EditText)findViewById(R.id.init_name);
		newPassWordEidt = (EditText)findViewById(R.id.init_password);
		asyncImageLoader.loadDrawable(null,myPhotoImg,"headImage.jpg", new ImageCallback() {
				
				@Override
				public void imageLoaded(ProgressBar progressBar,ImageView imageView,Drawable imageDrawable, String imageUrl, String tag) {
					// TODO Auto-generated method stub
					myPhotoImg.setImageBitmap(ImageManager.drawableToBitmap(imageDrawable,150.0f));
				}
			});
        handImgDialog = new HandImgDialog(mContext);
        handImgDialog.setCanceledOnTouchOutside(true);
        handImgDialog.setHandImgListener("cameraImg",new HandImgListener(){
        	public void handImg(){
        		if (handImgDialog != null && handImgDialog.isShowing()) {
        			handImgDialog.dismiss();
        		}
        		File sddir = new File(ImageManager.PHOTO_PATH );
        		if (!sddir.exists()) {
		              sddir.mkdirs();
		           }
        		File tempfile = new File(sddir.getAbsolutePath() + "headImage.jpg") ;
	    		Intent localIntent = new Intent("android.media.action.IMAGE_CAPTURE");
	    	    Uri localUri = Uri.fromFile(tempfile);
	    	    localIntent.putExtra("output", localUri);
	    	    startActivityForResult(localIntent, 0);
        	}
        }
        );
        
        handImgDialog.setHandImgListener("fileImg",new HandImgListener(){
        	public void handImg(){
        		if (handImgDialog != null && handImgDialog.isShowing()) {
        			handImgDialog.dismiss();
        		}
        		Intent intent = new Intent();
	    		intent.setType("image/*");
	    		intent.setAction(Intent.ACTION_GET_CONTENT);
	    		intent.addCategory(Intent.CATEGORY_OPENABLE);   
	    		startActivityForResult(intent,1);
	    		
        	}
        }
        );
	}



	@Override
	void initOnClick() {
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EditMyInfoActivity.this.finish();
				overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
			}
		});
		
		handHeadImg.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				// TODO Auto-generated method stub
				if (handImgDialog != null && !handImgDialog.isShowing()) {
					handImgDialog.show();
				}

			}
		});
		
		saveText.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if (newNameEdit.getText().toString().equals("")) {
					startAnimation(newNameEdit);
				} else if (newPassWordEidt.getText().toString().equals("")){
					startAnimation(newPassWordEidt);
				} else {
					requestHandInfo();
				}
				
				// 提交修改的数据，提交成功后保存头像到sd卡
				if (asSaveBitmap != null) {
					ImageManager.writeImgToSDcard("", "headImage.jpg", asSaveBitmap);
					if (asSaveBitmap != null && !asSaveBitmap.isRecycled()) {
						asSaveBitmap.recycle();
					}
					if (bitmap != null && !bitmap.isRecycled()) {
						bitmap.recycle();
					}
				}
				
				
			}
		});
		myPhotoImg.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if (handImgDialog != null && !handImgDialog.isShowing()) {
					handImgDialog.show();
				}
				
//				AlertDialog.Builder ab = new AlertDialog.Builder(mContext); 
//		        ab.setTitle("图片"); 
//		        String[] strs = new String[2];
//		        strs[0]= "相机拍摄";
//		        strs[1]= "本地图片";
//		        ab.setItems(strs,  new ImgAlterDialogClickListener()); 
//		        ab.show();
//				if (handImgDialog != null && !handImgDialog.isShowing()) {
//					handImgDialog.show();
//				}
		        
			}
		});
	}



	/**
	 * 将图片转换为二进制流
	 * @param bitmap
	 * @return
	 */
	public byte[] getBitmapAsByte(Bitmap bitmap){   
	    ByteArrayOutputStream out = new ByteArrayOutputStream();   
	    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);   
	    try {   
	        out.flush();   
	        out.close();   
	    } catch (IOException e) {   
	        e.printStackTrace();   
	    }   
	    return out.toByteArray();   
	} 
	
	public Bitmap getByteAsBimap(byte[] temp){   
		Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length); 
	    return bitmap;   
	} 
	
	  

	/**
	 * 将二进制转化为字符串
	 * @param by
	 * @return
	 * http://java.chinaitlab.com/dynamic/828909.html
	 */
	private String getStringFromByte(byte[] by) {
		String hs = "";
		String stmp = "";
		for (int i = 0; i < by.length; i++) {
			stmp = (java.lang.Integer.toHexString(by[i] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
		}
		return hs;
	}
	
	 /**
	  * 将bitmap转换为字符串
	  * @param bitmap
	  * @return
	  */
	 private String bitmaptoString(Bitmap bitmap) {
		 
		//将Bitmap转换成字符串
		 String string = null;
		 ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		 bitmap.compress(CompressFormat.PNG,100,bStream);
		 byte[] bytes = bStream.toByteArray();
		 string = Base64.encodeToString(bytes,Base64.DEFAULT);
		 return string;  
	 }
		 
	 /**
	  * 将字符串转化成bitmap
	  * @param string
	  * @return
	  */
	 public Bitmap stringtoBitmap(String string) {
		 Bitmap bitmap=null;
		 try {
			 byte[] bitmapArray;
			 bitmapArray=Base64.decode(string, Base64.DEFAULT);
			 bitmap=BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
		 return bitmap;
	 }
		 
		  
		    
		   
	
	
	
	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub
		/**
		 * 修改信息成功
		 */
		SharedPreferences.Editor editor = preferences.edit();
	    try {
			editor.putString("userId", response.getString("newUserId")).commit();
			editor.putString("userPassWord", newPassWordEidt.getText().toString()).commit();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//	   
//		ByteArrayInputStream bi = new ByteArrayInputStream(imgByte);
		
	}




	


}
